$(function () {
    /* var subentryList;
     var typeList;
     var level1AreaList;
     $.ajax({
         type: 'POST',
         url: '/meter/getAgreement',
         async: false,
         data: {},
         dataType: 'json',
         success: function (result) {
             if (result.code==666){
                 level1AreaList = result.data.level1AreaList;
                 subentryList=result.data.subentryList;
                 typeList=result.data.typeList;
             }else{
             }
         },
         error: function (XMLHttpRequest, textStatus, errorThrown) {
             if (XMLHttpRequest.status==555){
                 var layer;
                 layui.use(['layer', 'form'], function(){
                     layer = layui.layer
                     layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                         //do something
                         layer.close(index);
                         top.location.href="/login";
                     });
                 });
             }else{
                 var layer;
                 layui.use(['layer', 'form'], function(){
                     layer = layui.layer
                     layer.alert('页面加载失败',{icon:7}, function(index){
                         layer.close(index);
                     });
                 });
             }
         },
     });*/

    layui.use('table', function(){
        var table = layui.table;

        //方法级渲染
        table.render({
            elem: '#LAY_table_user'
            ,url: "/merchant/getMerchantList"
            ,cols: [[
                // {field:'id', title: 'ID', width:100, }
                {field:'id', title: '序号', width:100,}
                ,{field:'name', title: '姓名', width:200}
                ,{field:'phone', title: '手机号',  width:250}
                ,{field:'idcard', title: '身份证号', width:250}
                ,{field:'mail', title: '邮箱', width:250}
                ,{field:'addr', title: '地址',  width:300}
                ,{field:'accesstime', title: '开户时间', width:300}
                ,{field:'meters', title: '表记', width:350}
                ,{fixed:'right', title:'操作', toolbar: '#barDemo', width:300}
            ]]
            ,id: 'testReload'
            ,page: true
            ,height: 650
            ,response: {
                statusCode: 666 //规定成功的状态码，默认：0
            }
            // ,even:true //每行条纹
            ,limits: [10,15,20,25,30]
            ,limit: 10 //每页默认显示的数量
            ,toolbar:'#toolbarDemo'  //导出打印
            ,parseData:function (res) {
                return{
                    "code":res.code,
                    "msg":res.msg,
                    "count":res.data.merchantList.length,
                    "data":res.data.merchantList
                };
            }
            , done: function(res, curr, count){
                var userlist = res.data;
                console.log(res.data);
                var arr1 = [];//未启用
                var arr2 = [];//已启用
                var arr3 = [];//已销户
                for (var i=0;i<userlist.length;i++){
                    if (userlist[i].state==0) {
                        arr1.push(i);
                    }else if (userlist[i].state==1){
                        arr2.push(i)
                    } else if (userlist[i].state==-1){
                        arr3.push(i)
                    }
                }
                for (var k=0;k<arr2.length;k++){
                    $($($("[data-field='8']").children()[arr2[k]+1]).children()[1]).addClass("layui-btn-disabled");
                    $($($("[data-field='8']").children()[arr2[k]+1]).children()[1]).css("background-color","#B5B5B5");
                    $($($("[data-field='8']").children()[arr2[k]+1]).children()[2]).css("background-color","#B5B5B5");
                    $($($("[data-field='8']").children()[arr2[k]+1]).children()[2]).addClass("layui-btn-disabled");
                }
                for (var m=0;m<arr3.length;m++){
                    $($($("[data-field='8']").children()[arr3[m]+1]).children()[2]).css("background-color","#B5B5B5");
                    $($($("[data-field='8']").children()[arr3[m]+1]).children()[2]).addClass("layui-btn-disabled");
                    $($($("[data-field='8']").children()[arr3[m]+1]).children()[1]).css("background-color","#B5B5B5");
                    $($($("[data-field='8']").children()[arr3[m]+1]).children()[1]).addClass("layui-btn-disabled");
                    $($($("[data-field='8']").children()[arr3[m]+1]).children()[0]).css("background-color","#B5B5B5");
                    $($($("[data-field='8']").children()[arr3[m]+1]).children()[0]).addClass("layui-btn-disabled");
                }
            }
        });
        var $ = layui.$, active = {
            reload: function(){
                var demoReload = $('#demoReload');
                //执行重载
                table.reload('testReload', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        meterId: demoReload.val()
                    }
                });
            }
        };
        $('.layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        //监听行单击事件（单击事件为：rowDouble）
        //其中的user对应的是 table中的lay-filter="user"
        //监听行单击事件（单击事件为：rowDouble）
        //其中的user对应的是 table中的lay-filter="user"
        table.on('row(user)', function(obj){
            var data = obj.data;
            //标注选中样式
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
        });
        table.on('tool(user)', function(obj) {
            var id = obj.data.id;
            var meters = obj.data.meters;
            if(obj.event === 'oppen'){
                if (meters.toString().length>0) {
                    if (obj.data.state == 0 || obj.data.state == 2) {
                        layer.confirm('确定要启用该用户吗？', {
                            btn: ['确定', '取消'] //按钮
                        }, function () {
                            $.ajax({
                                type: 'POST',
                                url: '/merchant/oppenMerchant',
                                async: false,
                                data: {"id": id},
                                dataType: 'json',
                                success: function (result) {
                                    if (result.code == 666) {
                                        layer.alert('启用成功', {icon: 1}, function (index) {
                                            layer.closeAll();
                                            window.location.reload()
                                        });
                                    } else {
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    if (XMLHttpRequest.status == 555) {
                                        var layer;
                                        layui.use(['layer', 'form'], function () {
                                            layer = layui.layer
                                            layer.alert('未登录,请登录后操作', {icon: 7}, function (index) {
                                                //do something
                                                layer.close(index);
                                                top.location.href = "/login";
                                            });
                                        });
                                    } else {
                                        var layer;
                                        layui.use(['layer', 'form'], function () {
                                            layer = layui.layer
                                            layer.alert('页面加载失败', {icon: 7}, function (index) {
                                                layer.close(index);
                                            });
                                        });
                                    }
                                },
                            });
                        });
                    }
                }else{
                    var layer;
                    layui.use(['layer', 'form'], function () {
                        layer = layui.layer
                        layer.alert('未选择表记', {icon: 2}, function (index) {
                            layer.close(index);
                        });
                    });
                }
            }else if(obj.event === 'del'){
                if (obj.data.state==0||obj.data.state==2){
                    layer.confirm('确定要注销该用户吗？', {
                        btn: ['确定','取消'] //按钮
                    }, function() {
                        $.ajax({
                            type: 'POST',
                            url: '/merchant/pinHouseholds',
                            async: false,
                            data: {"id": id},
                            dataType: 'json',
                            success: function (result) {
                                if (result.code == 666) {
                                    layer.alert('注销成功', {icon: 1}, function (index) {
                                        layer.closeAll();
                                        window.location.reload()
                                    });
                                } else {
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                if (XMLHttpRequest.status == 555) {
                                    var layer;
                                    layui.use(['layer', 'form'], function () {
                                        layer = layui.layer
                                        layer.alert('未登录,请登录后操作', {icon: 7}, function (index) {
                                            //do something
                                            layer.close(index);
                                            top.location.href = "/login";
                                        });
                                    });
                                } else {
                                    var layer;
                                    layui.use(['layer', 'form'], function () {
                                        layer = layui.layer
                                        layer.alert('页面加载失败', {icon: 7}, function (index) {
                                            layer.close(index);
                                        });
                                    });
                                }
                            },
                        });
                    });
                }
            }else if(obj.event === 'modify'){
                /*$("#locationMod").addClass('active');
                $("#typeMod").removeClass("active")
                $("#descriptionMod").removeClass("active")*/
                var  meterStr = obj.data.meters.split("-");
                $.ajax({
                    type: 'POST',
                    url: '/meter/getMeterList',
                    async: false,
                    data: {},
                    dataType: 'json',
                    success: function (result) {
                        if (result.code==666){
                            console.log(result.data);
                            var merterList = result.data.meterList;
                            var datastr = ""
                            for (i=0;i<merterList.length;i++){
                                if (merterList[i].state==1&&(merterList[i].id).indexOf(obj.data.meters)==-1){
                                    datastr+=' {"value": "'+merterList[i].id+'", "title":"'+merterList[i].id+'", "disabled": true},';
                                }else{
                                    datastr+=' {"value": "'+merterList[i].id+'", "title":"'+merterList[i].id+'"},';
                                }
                            }
                            datastr = datastr.substring(0, datastr.length - 1);
                            var obj_groups = JSON.parse("["+datastr+"]");
                            layui.use(['transfer', 'layer', 'util'], function() {
                                var $ = layui.$
                                    , transfer = layui.transfer
                                    , layer = layui.layer
                                    , util = layui.util;
                                //实例调用
                                transfer.render({
                                    elem: '#test6'
                                    ,title: ["未选表记","已选表记"]
                                    , data: obj_groups
                                    ,width: 320
                                    ,height: 400
                                    ,value: meterStr
                                    , id: 'key456'//定义唯一索引
                                    ,onchange: function(obj, index){
                                        var x = transfer.getData('key456');
                                        var ids = "";
                                        console.log(x.length)
                                        for (var i=0;i<x.length;i++){
                                            ids+=x[i].value+",";
                                        }
                                        ids=ids.substring(0,ids.length-1);
                                        $("#meterCountMod").text(x.length);
                                        $("#meterIdsMod").text(ids);

                                    }
                                })
                            });
                        }else{
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (XMLHttpRequest.status==555){
                            var layer;
                            layui.use(['layer', 'form'], function(){
                                layer = layui.layer
                                layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                                    layer.close(index);
                                    top.location.href="/login";
                                });
                            });
                        }else{
                            var layer;
                            layui.use(['layer', 'form'], function(){
                                layer = layui.layer
                                layer.alert('页面加载失败',{icon:7}, function(index){
                                    layer.close(index);
                                });
                            });
                        }
                    },
                });
                layui.use(['layer', 'form'], function () {
                    var layer = layui.layer;
                    $('#div_step_modify').css("display","block");
                    layer.open({
                        type: 1,
                        title: ['用户修改', 'font-size:25px;font-weight:lighter;background-color:white;height:50px;margin-top:-2px'],
                        // skin: 'layui-layer-rim', //加上边框
                        area: ['800px', '700px'], //宽高
                        content:$('#div_step_modify'),
                        end: function () {
                            $('#div_step_modify').css("display","none");
                        }
                    })
                });
                $("#userMesg2").click();
                $("#inputIdMod").val(obj.data.id);
                $("#inputNameMod").val(obj.data.name);
                $("#inputPhoneMod").val(obj.data.phone);
                $("#inputPhone2Mod").val(obj.data.phone2);
                $("#inputPhone3Mod").val(obj.data.phone3);
                $("#inputIdCardMod").val(obj.data.idcard);
                $("#inputMailMod").val(obj.data.mail);
                $("#inputAddrMod").val(obj.data.addr);
                $("#sureNameMod").text(obj.data.name);
                $("#meterCountMod").text(meterStr.length);
                $("#meterIdsMod").text(obj.data.meters);
                $("#surePhoneMod").text(obj.data.phone);
                $("#surePhone2Mod").text(obj.data.phone2);
                $("#surePhone3Mod").text(obj.data.phone3);
                $("#sureIdCardMod").text(obj.data.idcard);
                $("#sureMailMod").text(obj.data.mail);
                $("#sureAddrMod").text(obj.data.addr);
            }

        });

    });
});
$("#add").click(function () {

    /*$("#location").addClass('active');
    $("#type").removeClass("active")
    $("#description").removeClass("active")*/
    $.ajax({
        type: 'POST',
        url: '/meter/getMeterList',
        async: false,
        data: {},
        dataType: 'json',
        success: function (result) {
            if (result.code==666){
                console.log(result.data);
                var merterList = result.data.meterList;
                var datastr = ""
                for (i=0;i<merterList.length;i++){
                    if (merterList[i].state==1){
                        datastr+=' {"value": "'+merterList[i].id+'", "title":"'+merterList[i].id+'", "disabled": true},';
                    }else{
                        datastr+=' {"value": "'+merterList[i].id+'", "title":"'+merterList[i].id+'"},';
                    }
                }
                datastr = datastr.substring(0, datastr.length - 1);
                var obj_groups = JSON.parse("["+datastr+"]");
                layui.use(['transfer', 'layer', 'util'], function() {
                    var $ = layui.$
                        , transfer = layui.transfer
                        , layer = layui.layer
                        , util = layui.util;
                    //实例调用
                    transfer.render({
                        elem: '#test7'
                        ,title: ["未选表记","已选表记"]
                        , data: obj_groups
                        ,width: 320
                        ,height: 400
                        , id: 'key123'//定义唯一索引
                        ,onchange: function(obj, index){
                            var x = transfer.getData('key123');
                            var ids = "";
                            console.log(x.length)
                            for (var i=0;i<x.length;i++){
                                ids+=x[i].value+",";
                            }
                            console.log(ids) //获得被穿梭时的数据
                            ids=ids.substring(0,ids.length-1);
                            $("#meterCount").text(x.length);
                            $("#meterIds").text(ids);

                        }
                    })
                });
            }else{
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status==555){
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                        layer.close(index);
                        top.location.href="/login";
                    });
                });
            }else{
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('页面加载失败',{icon:7}, function(index){
                        layer.close(index);
                    });
                });
            }
        },
    });


    layui.use(['layer', 'form'], function () {
        var layer = layui.layer;
        $('#div_step').css("display","block");
        layer.open({
            type: 1,
            title: ['用户开户', 'font-size:25px;font-weight:lighter;background-color:white;height:50px;margin-top:-2px'],
            // skin: 'layui-layer-rim', //加上边框
            area: ['800px', '700px'], //宽高
            content:$('#div_step'),
            end: function () {
                $('#div_step').css("display","none");
            }
        })

    });
    $("#userMesg1").click();

});
function valueChange(obj) {
    var textVal = $(obj).val();
    var idval  = $(obj).attr("id");
    var idStr = "sure"+idval.replace("input","");
    $("#"+idStr).text(textVal);
}
function oppenAccount() {
    var name = $("#inputName").val();
    var phone = $("#inputPhone").val();
    var phone2 = $("#inputPhone2").val();
    var phone3 = $("#inputPhone3").val();
    var id_card = $("#inputIdCard").val();
    var mail = $("#inputMail").val();
    var addr = $("#inputAddr").val();
    var meters = $("#meterIds").text();
    if (name==null||""==name.trim()){
        layer.msg('姓名信息为空', {icon: 2,time:2000});
    }else if (phone==null||""==phone.trim()){
        layer.msg('手机号为空', {icon: 2,time:2000});
    }else if (checkPhone(phone)){
        layer.msg('手机号格式有误', {icon: 2,time:2000});
    }else if (phone2.length>0&&checkPhone(phone2)){
        layer.msg('第二联系方式格式有误', {icon: 2,time:2000});
    }
    else if (phone3.length>0&&checkPhone(phone3)){
        layer.msg('第三联系方式格式有误', {icon: 2,time:2000});
    }else{
        $.ajax({
            type: 'POST',
            url: '/merchant/addMerchant',
            async: false,
            data: {"name":name,"phone":phone,"phone2":phone2,"phone":phone,"phone3":phone3,"idcard":id_card,"addr":addr,"mail":mail,"meters":meters},
            dataType: 'json',
            success: function (result) {
                if (result.code==666){
                    layer.alert('开户成功', {icon: 1},function (index) {
                        layer.closeAll();
                        $('#div_step').css("display","none");
                        window.location.reload()
                    });

                }else{
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.status==555){
                    var layer;
                    layui.use(['layer', 'form'], function(){
                        layer = layui.layer
                        layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                            //do something
                            layer.close(index);
                            top.location.href="/login";
                        });
                    });
                }else{
                    var layer;
                    layui.use(['layer', 'form'], function(){
                        layer = layui.layer
                        layer.alert('页面加载失败',{icon:7}, function(index){
                            layer.close(index);
                        });
                    });
                }
            },
        });
    }

}
function checkPhone(phone){
    if(!(/^1[3456789]\d{9}$/.test(phone))){
        return true;
    }else{
        return false;
    }
}
function modifyMerchant() {
    var id = $("#inputIdMod").val();
    var name = $("#inputNameMod").val();
    var phone = $("#inputPhoneMod").val();
    var phone2 = $("#inputPhone2Mod").val();
    var phone3 = $("#inputPhone3Mod").val();
    var id_card = $("#inputIdCardMod").val();
    var mail = $("#inputMailMod").val();
    var addr = $("#inputAddrMod").val();
    var meters = $("#meterIdsMod").text();
    if (name==null||""==name.trim()){
        layer.msg('姓名信息为空', {icon: 2,time:2000});
    }else if (phone==null||""==phone.trim()){
        layer.msg('手机号为空', {icon: 2,time:2000});
    }else if (checkPhone(phone)){
        layer.msg('手机号格式有误', {icon: 2,time:2000});
    }else if (phone2.length>0&&checkPhone(phone2)){
        layer.msg('第二联系方式格式有误', {icon: 2,time:2000});
    }
    else if (phone3.length>0&&checkPhone(phone3)){
        layer.msg('第三联系方式格式有误', {icon: 2,time:2000});
    }else{
        $.ajax({
            type: 'POST',
            url: '/merchant/modifyMerchant',
            async: false,
            data: {"id":id,"name":name,"phone":phone,"phone2":phone2,"phone":phone,"phone3":phone3,"idcard":id_card,"addr":addr,"mail":mail,"meters":meters},
            dataType: 'json',
            success: function (result) {
                if (result.code==666){
                    layer.alert('修改成功', {icon: 1},function (index) {
                        layer.closeAll();
                        $('#div_step_modify').css("display","none");
                        window.location.reload()

                    });

                }else{
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.status==555){
                    var layer;
                    layui.use(['layer', 'form'], function(){
                        layer = layui.layer
                        layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                            //do something
                            layer.close(index);
                            top.location.href="/login";
                        });
                    });
                }else{
                    var layer;
                    layui.use(['layer', 'form'], function(){
                        layer = layui.layer
                        layer.alert('页面加载失败',{icon:7}, function(index){
                            layer.close(index);
                        });
                    });
                }
            },
        });
    }
}